package com.example.system.controller;

import com.example.starter.util.Response;
import com.example.starter.webmvc.valid.CreateValid;
import com.example.starter.webmvc.valid.UpdateValid;
import com.example.system.constant.PM;
import com.example.system.convert.RoleConvert;
import com.example.system.dto.RoleDto;
import com.example.system.entity.Role;
import com.example.system.service.IRoleService;
import com.example.system.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RequestMapping("/role")
@RequiredArgsConstructor
@RestController
public class RoleController {

    private final IRoleService service;

    @PreAuthorize("hasAuthority('"+ PM.SYS_ROLE_WRITE +"')")
    @PostMapping
    public Response<Boolean> create(@RequestBody @Validated(CreateValid.class) RoleDto roleDto) {
        service.create(roleDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_ROLE_WRITE +"')")
    @PutMapping
    public Response<Boolean> update(@RequestBody @Validated(UpdateValid.class) RoleDto roleDto) {
        service.update(roleDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.GRANT_ROLE_AUTHORIZATION +"')")
    @PutMapping("/grant/{id}/authorities")
    @Deprecated
    public Response<Boolean> grantAuthorities(@PathVariable("id") Long roleId, @RequestBody List<Long> authoritiesId) {
        service.grantAuthorities(roleId, authoritiesId);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_ROLE_WRITE +"')")
    @DeleteMapping("/{id}")
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        service.removeById(id);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_ROLE_READ +"')")
    @GetMapping("/{id}")
    public Response<RoleVo> findById(@PathVariable("id") Long id) {
        Role role = service.getById(id);
        return Response.ok(RoleConvert.INSTANCE.toRoleVo(role));
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_ROLE_READ +"')")
    @GetMapping("/list")
    public Response<List<RoleVo>> listAll() {
        return Response.ok(service.listAll());
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_ROLE_READ +"')")
    @GetMapping({"/{id}/authorities-joins", "/{id}/authority-joins"})
    public Response<List<Long>> listAuthorityJoins(@PathVariable("id") Long roleId) {
        return Response.ok(service.listAuthorityIdByRoleId(roleId));
    }

}
